﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Janus.Windows.GridEX;
using OrderAggregator.DataStorage;
using SortOrder = Janus.Windows.GridEX.SortOrder;

namespace OrderAggregator.UI
{
    public partial class TableEditControl : BaseEditListControl
    {
        public TableEditControl()
        {
            InitializeComponent();

            _grid.SelectionChanged += _grid_SelectionChanged;
            _grid.ColumnButtonClick += grid_ColumnButtonClick;

            OnReadOnlyChanged();
        }

       

        
        /// <summary>
        /// Table
        /// </summary>
        [Browsable(false)]
        public DataTable Table
        {
            set
            {
                CustomizeGridTable(value, _grid.RootTable);
                _grid.DataSource = value;
            }
            get
            {
                return (DataTable) _grid.DataSource;
            }
        }

       

        public override DataRow SelectedRow
        {
            get
            {
                var gridRow = _grid.GetRow();

                if (gridRow == null)
                {
                    return null;
                }

                var view = (DataRowView) gridRow.DataRow;

                return view == null ? null : view.Row;
            }
            set
            {
                if (SelectedRow == value)
                {
                    return;
                }

                var row = _grid.GetRow(value);

                if (row != null)
                {
                    _grid.Row = row.Position;
                }
            }
        }
               
        
        protected override void OnReadOnlyChanged()
        {
            if (ReadOnly)
            {
                _grid.AllowDelete = InheritableBoolean.False;
                _grid.AllowAddNew = InheritableBoolean.False;
                _grid.AllowEdit = InheritableBoolean.False;
            }
            else
            {
                _grid.AllowDelete = InheritableBoolean.True;
                _grid.AllowAddNew = InheritableBoolean.True;
                _grid.AllowEdit = InheritableBoolean.True;
            }
        }

        private void _grid_SelectionChanged(object sender, EventArgs e)
        {
            RaiseSelectedRowChanged();
        }

        private static void CustomizeGridTable(DataTable table, GridEXTable rootTable)
        {
            rootTable.Columns.Clear();
            rootTable.Groups.Clear();
            rootTable.SortKeys.Clear();

            if (table == null)
            {
                return;
            }

            var storage = (Storage) table.DataSet;

            if (table is Storage.OrganizationDataTable ||
                table is Storage.DepartmentDataTable
                )
            {
                var column = CreateNameColumn();
                rootTable.Columns.Add(column);
                rootTable.SortKeys.Add(new GridEXSortKey(column));
            }
            else if (table is Storage.OrganizationProductRelationDataTable)
            {
                var column = CreateOrganizationColumn(storage, false);
                rootTable.Columns.Add(column);
                rootTable.Groups.Add(new GridEXGroup(column, SortOrder.Descending));

                column = CreateProductColumn(storage, false);
                rootTable.Columns.Add(column);

                column = new GridEXColumn();
                column.Caption = "Код Продукта";
                column.DataMember = "ProductCode";
                rootTable.Columns.Add(column);
            }
            else if (table is Storage.ProductDataTable)
            {
                var column = CreateNameColumn();
                rootTable.Columns.Add(column);
                rootTable.SortKeys.Add(new GridEXSortKey(column));

                column = new GridEXColumn();
                column.Caption = "Код Продукта";
                column.DataMember = "Code";
                rootTable.Columns.Add(column);

                column = CreateDropDownColumn("Цех производства", "DepartmentId", storage.Department);
                rootTable.Columns.Add(column);

                column = new GridEXColumn();
                column.Caption = "Единицы измерения";
                column.DataMember = "UnitName";
                column.EditType = EditType.Combo;
                
                {
                    column.HasValueList = true;
                    var valueList = column.ValueList;

                    foreach (string unitName in new []{"шт", "кг", "г"})
                    {
                        var item = new GridEXValueListItem();
                        item.Value = unitName;
                        item.Text = unitName;
                        valueList.Add(item);
                    }
                }
                rootTable.Columns.Add(column);
            }
            else if (table is Storage.DiscountDataTable)
            {
                var column = CreateOrganizationColumn(storage, true);
                rootTable.Columns.Add(column);
                rootTable.Groups.Add(new GridEXGroup(column, SortOrder.Descending));

                column = CreateProductColumn(storage, true);
                rootTable.Columns.Add(column);

                column = CreateDropDownColumn("Формула", "FormulaId", storage.Formula, true);
                rootTable.Columns.Add(column);
                
            }
            else if (table is Storage.FormulaDataTable)
            {
                var column = CreateNameColumn();
                rootTable.Columns.Add(column);
                rootTable.SortKeys.Add(new GridEXSortKey(column));

                column = new GridEXColumn();
                column.Caption = "Формула";
                column.DataMember = "Expression";
                column.EditType = EditType.NoEdit;
                column.ButtonStyle = ButtonStyle.Ellipsis;
                column.ButtonDisplayMode = CellButtonDisplayMode.Always;
                rootTable.Columns.Add(column);
            }
        }

        private void grid_ColumnButtonClick(object sender, ColumnActionEventArgs e)
        {
            var gridRow = _grid.GetRow();
            var gridCell = gridRow.Cells[e.Column];

            var formula = gridCell.Value as string;

            if (UIManager.EditFormula(ref formula))
            {
                gridCell.Value = formula;
            }
        }

        private static GridEXColumn CreateNameColumn()
        {
            var column = new GridEXColumn();
            column.DataMember = "Name";
            column.Caption = "Имя";
            
            return column;
        }

        private static GridEXColumn CreateDropDownColumn(
            string columnCaption,
            string dataMember,
            DataTable dropDownDataSource
            )
        {
            return CreateDropDownColumn(columnCaption, dataMember, dropDownDataSource, false);
        }

        private static GridEXColumn CreateDropDownColumn(
            string columnCaption, 
            string dataMember, 
            DataTable dropDownDataSource,
            bool nullable
            )
        {
            var column = new GridEXColumn();
            column.Caption = columnCaption;
            column.DataMember = dataMember;
            column.EditType = EditType.DropDownList;

            column.HasValueList = true;
            var valueList = column.ValueList;

            if (nullable)
            {
                column.NullText = "(пусто)";
                valueList.Add(new GridEXValueListItem(System.DBNull.Value, column.NullText));
            }

            DataView view = new DataView(dropDownDataSource);
            view.Sort = "Name";
            foreach (DataRowView rowView in view)
            {
                var row = rowView.Row;
                valueList.Add(new GridEXValueListItem(row["Id"], row["Name"] as string));
            }
            column.EditValueList = valueList;
            
            return column;
        }

        private static GridEXColumn CreateOrganizationColumn(Storage storage, bool nullable)
        {
            var column = CreateDropDownColumn("Организация", "OrganizationId", storage.Organization, nullable);
            column.Width = 100;
            return column;
        }

        private static GridEXColumn CreateProductColumn(Storage storage, bool nullable)
        {
            return CreateDropDownColumn("Продукт", "ProductId", storage.Product, nullable);
        }
    }
}
